# -*- coding: utf-8 -*-
"""
@Time ： 2020/11/18 21:28
@Auth ： Mr. William 1052949192
@Company ：特斯汀学院 @testingedu.com.cn
@Function ：数据驱动运行入口
"""
import time
from common.Logger import logger
from common.Excel import get_reader, get_writer
from common.mail import Mail
from common.mysql import Mysql
from inter.keywords import Inter


def runcase(line,writer,i):
    """
    运行每一行用例
    :param line: 数据驱动里面每一行用例数据
    :return:
    """
    global obj

    if len(line[0]) > 0 or len(line[1]) > 0:
        # 分组信息不用执行
        return

    try:
        func = obj.__getattribute__(line[3])
    except Exception as e:
        logger.error('关键字%s不存在' % line[3])
        writer.write(i,7,'FAIL')
        writer.write(i, 9, '关键字%s不存在' % line[3])
        return

    try:
        params = line[4:]
        params = params[:params.index('')]
        # logger.error('关键字%s参数错误%s' % (line[3], params))
        func(*params)
    except Exception as e:
        logger.error('关键字%s参数错误%s' % (line[3], line))
        writer.write(i, 7, 'FAIL')
        writer.write(i, 9, '关键字%s参数错误%s' % (line[3], line))
        logger.exception(e)
        return


# 初始化数据库
mysql = Mysql()
mysql.init_mysql()

# 配置需要运行的用例
casename = 'HTTP接口用例-all.xlsx'
# excel读写对象
reader = get_reader('lib/cases/' + casename)
writer = get_writer('lib/cases/' + casename,
                    'lib/cases/result-' + casename)

# 定义需要反射的对象
obj = Inter(writer)

sheetname = reader.get_sheets()
# 记录用例运行的开始时间
stattime = str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
writer.set_sheet(sheetname[0])
writer.write(1, 3, stattime)

logger.debug(sheetname)
for sheet in sheetname:
    # 设置当前读取的sheet页面
    reader.set_sheet(sheet)
    writer.set_sheet(sheet)

    lines = reader.readline()
    for i in range(len(lines)):
        line = lines[i]
        logger.debug(line)
        # 当前读哪一行，我就写哪一行
        writer.row = i
        runcase(line,writer,i)

# 设置到第一个sheet页面
writer.set_sheet(sheetname[0])
# 记录用例运行的开始时间
endtime = str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
writer.write(1, 4, endtime)

# 保存结果
writer.save_close()

# 发送邮件
mail = Mail()
mail.mail_info['filepaths'] = ['.\\lib\\cases\\result-' + casename]
mail.mail_info['filenames'] = ['result-' + casename]

text = mail.get_summary('.\\lib\\cases\\result-' + casename)
trs = mail.get_details('.\\lib\\cases\\result-' + casename)
text = text.replace('mailbody', trs)

mail.send(text)
